package com.example.lt.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.lt.mapper.ListSongMapper;
import com.example.lt.pojo.entity.ListSong;
import com.example.lt.pojo.entity.Song;
import com.example.lt.pojo.vo.SongVO;
import com.example.lt.service.ListSongService;
import com.example.lt.service.SongService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author 小涛Tao
 * @Date: 2024/06/02/19:11
 * version 1.0 注释：
 **/
@Slf4j
@Service
@RequiredArgsConstructor
public class ListSongServiceImpl extends ServiceImpl<ListSongMapper, ListSong> implements ListSongService {

    private final SongService songService;

    /**
     * 根据歌单id查询歌单中的所有歌曲id
     *
     * @param songListId
     */
    @Cacheable(value = "songList", key = "#songListId",  unless = "#result == null")
    public List<SongVO> getSongList(int songListId) {
        log.info("此次获取歌单：{} 的所有歌曲没有走缓存", songListId);
        // 获取歌单中的歌曲id
        List<ListSong> list = lambdaQuery().eq(ListSong::getSongListId, songListId).list();

        if (list.isEmpty()){
            return null;
        }

        // 通过stream流的方式把 songId 属性抽离成集合，然后查询song的信息
        List<Integer> songIds = list.stream().map(ListSong::getSongId).collect(Collectors.toList());
        List<Song> songList = songService.listByIds(songIds);

        List<SongVO> songVOList = new ArrayList<>();
        for (Song song : songList) {
            SongVO songVO = BeanUtil.copyProperties(song, SongVO.class);
            songVOList.add(songVO);
        }

        return songVOList;
    }

}
